import store from "@/store"
import { userActionType } from "@/store/modules/user"
import { handleUrlParams } from "@/utils/index"
import { getWebsocketUrl } from "@/utils/settings"

export default {
  socketTask: null,
  // 初始化websocket
  initializing: false, //是否正在初始化，防止多次初始化
  initPromiseList: [], //初始化的promise队列，防止多次初始化
  init() {
    return new Promise(async (resolve, reject) => {
      if (this.socketTask) {
        return
      }
      // 如果正在初始化，将promise放入队列
      if (this.initializing) {
        this.initPromiseList.push({ resolve, reject })
        return
      }
      this.initializing = true
      await this.connect()
      let that = this
      //每个30s发送一次心跳
      setInterval(() => {
        that.send({
          content: "心跳",
          contentType: 1,
          messageType: 0,
        })
      }, 30000)
      // 监听websocket关闭
      this.socketTask.onClose(async (obj) => {
        console.log(JSON.stringify(obj), "websocket关闭")
        //重新连接
        await this.connect()
      })
      // 监听websocket错误
      this.socketTask.onError(async (obj) => {
        console.log(JSON.stringify(obj), "websocket错误")
        //重新连接
        await this.connect()
      })
      // 执行队列中的promise
      this.initPromiseList.forEach((item) => {
        item.resolve()
      })
      this.initializing = false
      this.initPromiseList = []
      resolve()
    })
  },
  //连接 websocket
  connecting: false, //是否正在连接，防止多次连接
  connectPromiseList: [], //连接的promise队列，防止多次连接
  connect() {
    return new Promise(async (resolve, reject) => {
      // 如果正在连接，将promise放入队列
      if (this.connecting) {
        this.connectPromiseList.push({ resolve, reject })
        return
      }
      this.connecting = true
      const userInfo = await store.dispatch(userActionType.action.userInfo)
      this.socketTask = uni.connectSocket({
        url: handleUrlParams(getWebsocketUrl(), {
          "k-Authorization": userInfo.token,
        }),
        success: (res) => {
          console.log(res, "成功连接 websocket 服务器")
          resolve(res)
        },
        fail: (err) => {
          console.log(err, "连接 websocket 服务器失败")
          reject(err)
        },
        complete: () => {
          this.connecting = false
          //连接成功后，执行队列中的promise
          this.connectPromiseList.forEach((item) => {
            item.resolve()
          })
          this.connectPromiseList = []
        },
      })
    })
  },
  //发送消息
  reTrySendCount: 3, //发送消息失败尝试重新发送的次数
  send(obj) {
    return new Promise(async (resolve, reject) => {
      if (!this.socketTask) {
        await this.init()
      }
      this.socketTask.send({
        data: JSON.stringify(obj),
        success: () => {
          resolve()
        },
        fail: async (err) => {
          console.log(JSON.stringify(err), "发送websocket消息失败")
          //重新连接
          this.socketTask.close()
          await this.connect()
          //重新发送
          let that = this
          setTimeout(() => {
            if (that.reTrySendCount > 0) {
              that.reTrySendCount--
              that.send(obj).then(() => {
                that.reTrySendCount = 3
              })
            }
          }, 2000)
          reject()
        },
      })
    })
  },
  //向服务器通信，跟踪当前用户所处的页面
  // eventType 1:进入页面，2:离开页面
  async trackCurrentPage(pageName, checkType = "", eventType = "") {
    try {
      await this.send({
        content: pageName,
        contentType: 1,
        messageType: 1,
        checkType: checkType,
        eventType: eventType,
      })
    } catch (e) {
      console.log(e,'error');
    }
  },
}
